import { app, BrowserWindow, dialog } from "electron";
import path, { join } from "path";
// import storage from "electron-localstorage"; //删除本地存储的token，需要单独配置，麻烦，此处采用 partition: String(+new Date()) 
// const  storage =require('electron-localstorage');
// storage.setStoragePath(path.join(__dirname, 'db.json'))

// const Store = require('electron-store'); //electron-store和vuex pinna一样
// const store = new Store();
// store.set('unicorn', '🦄');
// console.log(store.get('unicorn'));
// //=> '🦄'

// // Use dot-notation to access nested properties
// store.set('foo.bar', true);
// console.log(store.get('foo'));
// //=> {bar: true}

// store.delete('unicorn');
// console.log(store.get('unicorn'));
// //=> undefined

import autoUpdate from "../modules/autoUpdate";
import { closeDevTools, openDevTools } from "../utils/devtools";
import { getIcon } from "../utils/icon";
import { ipcMainHandle } from "../utils/ipcMain";

const createMainWin = (): BrowserWindow => {
    const win = new BrowserWindow({
        width: 1420,
        height: 800,
        icon: getIcon(),
        frame: true, // 让桌面应用没有边框，这样菜单栏也会消失,为true则 win.setMenuBarVisibility(false)
        // fullscreen: false, // 全屏
        useContentSize: false,
        maximizable: true,
        resizable: true, // 不允许用户改变窗口大小,
        // titleBarStyle: "hidden", // frame为false开启titleBarStyle ，titleBarOverlay才能被开启，
        // titleBarOverlay: {
        //     color: "#f8f8f8",
        //     symbolColor: "black"
        // },
        // titleBarStyle: "hiddenInset",
        // backgroundColor: "#2e2c29",
        // autoHideMenuBar: true, // 隐藏菜单栏
        title: "electronApp",
        webPreferences: {
            nodeIntegration: true, // 是否集成nodejs 解决require 识别问题
            contextIsolation: true, // 是否开启上下文隔离
            preload: join(__dirname, "../preload/index.js"),
            // partition: String(+new Date()) //使用新的缓存，相当于每次使用隐身模式打开。
            // devTools: true,
            // webSecurity: false, //跨域 contextIsolation = true参数，设置后主进程和渲染进程之间的通信方式就要换一种写法
            // backgroundThrottling: false,
            // nodeIntegrationInWorker: false //多线程
        }
    });
    win.setMenuBarVisibility(false)

    win.webContents.on("did-finish-load", () => {
        // 利用localStorage存储win.id
        win.webContents.executeJavaScript(`localStorage.setItem("electronMainWinId",${win.id})`);
        win ?.webContents.send("main-process-message", new Date().toLocaleString());
    });
    // const ses = win.webContents.session //官方提供 管理浏览器会话、cookie、缓存、代理设置等 ；session 模块可用于创建新的 session 对象。
    const clearObj = {
            storages: ['appcache', 'filesystem', 'localstorage', 'shadercache', 'websql', 'serviceworkers', 'cachestorage'],
        };
       //主进程使用，清空electron缓存和partition: String(+new Date()) 类似
        if (win) {
            win.webContents.session.clearStorageData(clearObj);
    }
    win.on("close", (event) => {
        event.preventDefault();
        if (dialog.showMessageBoxSync(win, {
            // type String - 可以是 "none", "info", "error", "question" 或 "warning"
            type: "info",
            buttons: ["直接退出","最小化到托盘"],
            title: "提示",
            message: "确定要退出吗？",
            defaultId: 0,
            cancelId: 1,
            noLink:true, // 按钮并列显示在右下角
			icon:getIcon(),
        }) === 1) {
            win.hide();
        } else {
            // storage.removeItem(`Cusertoken`);
            // storage.clear()
            app.exit();
        }
    });


    if (app.isPackaged) {
        win.loadFile(join(__dirname, "../../index.html"));
    } else {
        const url = `http://${process.env["VITE_DEV_SERVER_HOST"]}:${process.env["VITE_DEV_SERVER_PORT"]}`;

        win.loadURL(url); //非开发模式使用

        win.loadURL(url).finally(() => openDevTools(win)); //封装的调试工具，右下角打开app
        // win.loadURL(url).finally(() => closeDevTools(win)); //封装的调试工具，关闭会杀掉进程
    }

	/**
	 * 检查更新
	 */
    ipcMainHandle("checkUpdate", async () => {
        return await autoUpdate(win);
    });

    return win;
};

export default createMainWin;
